import React, { useState } from 'react';


const App = () => {
  const [list, setList] = useState([{
    "title": "吃饭",
    "money": -100,
    "date": "2020-01-01",
    "remark": "吃的是火锅"
  }, {
    "title": "购物",
    "money": -200000,
    "date": "2020-01-02",
    "remark": "买了一辆汽车"
  }, {
    "title": "住宿",
    "money": -300,
    "date": "2020-01-03",
    "remark": "住的是五星级酒店"
  }, {
    "title": "工资",
    "money": 300000,
    "date": "2020-01-04",
    "remark": "工资到账"
  }])
  const [title, setTitle] = useState('');
  const [money, setMoney] = useState(0);
  const [date, setDate] = useState('');
  const [remark, setRemark] = useState('');
  const handleClick = () => {
    const newList = [...list]
    newList.push({
      title,
      money,
      date,
      remark
    })
    setList(newList)
  }
  const sum = list.reduce((acc, cur) => acc + cur.money, 0)
  // 求和list， 注意只要money字段为正数的
  const sum1 = list.filter(item => item.money > 0).reduce((acc, cur) => acc + cur.money, 0)
  // 求和list， 注意只要money字段为负数的
  const sum2 = list.filter(item => item.money < 0).reduce((acc, cur) => acc + cur.money, 0)


  // 帮我写一个弹框， 可以实现对 list 追加数据


  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>
              账目
            </th>
            <th>
              费用
            </th>
            <th>
              日期
            </th>
            <th>
              备注
            </th>
          </tr>
        </thead>
        <tbody>
          {
            list
              .map(
                (item, index) => {
                  return (
                    <tr key={index}>
                      <td>{item.title}</td>
                      <td>{item.money}</td>
                      <td>{item.date}</td>
                      <td>{item.remark}</td>
                    </tr>
                  )
                }
              )
          }
        </tbody>
        <tfoot>
          <tr>
            <td colSpan="4">
              <button>添加</button>
              <span>收入：{sum1}</span>
              <span>支出：{sum2}</span>
              <span>小记：{sum}</span>
            </td>
          </tr>
        </tfoot>
      </table>
      {/*   // 帮我写一个弹框， 可以实现对 list 追加数据 */}
      <div>
        <input type="text" name="" id="" value={title} onChange={e => setTitle(e.target.value)} />
        <input type="text" name="" id="" value={money} onChange={e => setMoney(e.target.value)} />
        <input type="text" name="" id="" value={date} onChange={e => setDate(e.target.value)} />
        <input type="text" name="" id="" value={remark} onChange={e => setRemark(e.target.value)}
        />
        <button onClick={() => handleClick()}>添加</button>
      </div>


    </div>
  )
}

export default App